package com.lm.kaptcha.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.code.kaptcha.Producer;
import com.lm.kaptcha.entry.CaptchaEntity;
import com.lm.kaptcha.mapper.CaptchaMapper;
import com.lm.kaptcha.utils.DateUtils;
import io.micrometer.core.instrument.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.awt.image.BufferedImage;
import java.util.Date;

@Service
public class CaptchaService extends ServiceImpl<CaptchaMapper, CaptchaEntity> {

    @Resource
    private CaptchaMapper captchaMapper;

    @Autowired
    private Producer producer;

    public BufferedImage getCaptcha(String uuid) {
        if(StringUtils.isBlank(uuid)){
            throw new RuntimeException("uuid不能为空");
        }
        //生成文字验证码
        String code = producer.createText();

        CaptchaEntity  captchaEntity = new CaptchaEntity ();
        captchaEntity.setUuid(uuid);
        captchaEntity.setCode(code);
        //5分钟后过期
        captchaEntity.setExpireTime(DateUtils.addDateMinutes(new Date(), 5));
        this.captchaMapper.insert(captchaEntity);

        return producer.createImage(code);
    }

    public boolean validate(String uuid, String code) {
        CaptchaEntity captchaEntity = this.getOne(new QueryWrapper<CaptchaEntity >().eq("uuid", uuid));
        if(captchaEntity == null){
            return false;
        }

        //删除验证码
        this.removeById(uuid);

        if(captchaEntity.getCode().equalsIgnoreCase(code) && captchaEntity.getExpireTime().getTime() >= System.currentTimeMillis()){
            return true;
        }

        return false;
    }
}